package dev.sharp.ymcloud.cloud;

import android.app.AlertDialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.stardust.app.GlobalAppContext;
import com.stardust.autojs.util.FloatingPermission;

import java.util.Timer;
import java.util.TimerTask;

import dev.sharp.ymcloud.App;
import dev.sharp.ymcloud.R;
import dev.sharp.ymcloud.model.script.ScriptFile;
import dev.sharp.ymcloud.network.UserService;
import dev.sharp.ymcloud.network.entity.user.User;
import dev.sharp.ymcloud.network.http.WsClient;

import static com.stardust.autojs.util.FloatingPermission.manageDrawOverlays;

public class MessageHelper {
    private Context mContext;
    private WsClient wsClient;

    public MessageHelper(WsClient pwsClient) {
        wsClient = pwsClient;
        mContext = pwsClient.getContext();
    }

    public void setMessage(String msg) {
        if (android.text.TextUtils.isEmpty(msg)) {
            return;
        }
        User user = UserService.getInstance().getUser();
        if (user == null) {
            return;
        }
        try {
            int deviceId = user.deviceId;
            String[] paras = msg.split(":");
            if (paras.length == 2) {
                switch (paras[0].trim()) {
                    case "exec"://执行脚本
                        int scriptid = Integer.parseInt(paras[1]);
                        execScript(scriptid, deviceId);
                        break;
                    case "execwithargs"://执行脚本，并需要下载启动参数
                        int scriptid1 = Integer.parseInt(paras[1]);
                        execScript(scriptid1, deviceId);
                        break;
                    case "mockloc"://模拟位置
                        String str = paras[1];
                        String[] strs = str.split(",");
                        double lat = Double.parseDouble(strs[0]);
                        double lng = Double.parseDouble(strs[1]);
                        mockLocation(lat, lng);
                        break;
                    case "dingdong"://查找设备
                        //playSound();
                        dlg("查找设备", " Were you looking for me?");
                        playFindSound();
                        break;
                    default:
                        break;
                }
            } else if (paras.length == 1) {
                switch (paras[0].trim()) {
                    case "stopallscripts"://停止全部脚本
                        ScriptsHelper.stopAll();
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception ex) {
            wsClient.sendMessage("error");
        }
    }

    private void dlg(String title, String content) {
        new Handler(Looper.getMainLooper()).post(
                () -> {
                    if (!FloatingPermission.canDrawOverlays(GlobalAppContext.get())) {
                        Toast.makeText(GlobalAppContext.get(), R.string.text_no_floating_window_permission, Toast.LENGTH_SHORT).show();
                        manageDrawOverlays(GlobalAppContext.get());
                        return;
                    }
                    AlertDialog alertDialog1 = new AlertDialog.Builder(App.getApp().getApplicationContext())
                            .setTitle(title)//标题
                            .setMessage(content)//内容
                            .setIcon(R.drawable.ymcloud_material)//图标
                            .setPositiveButton("关闭", (dialogInterface, i) -> dialogInterface.dismiss())
                            .create();
                    alertDialog1.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                    alertDialog1.show();
                    final Timer t = new Timer();
                    t.schedule(new TimerTask() {
                        public void run() {
                            alertDialog1.dismiss();
                            t.cancel();
                        }
                    }, 30000);
                }
        );
    }

    private void playFindSound() {
        SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);
        soundPool.load(mContext, R.raw.dingdong, 1);
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                soundPool.play(1, 1, 1, 0, 0, 1);
            }
        });
    }

    private void execScript(int scriptid, int deviceid) {
        Thread t = new Thread(
                () -> {
                    try {
                        ScriptFile sf = ScriptsHelper.LoadScript(mContext, scriptid, deviceid);
                        ScriptsHelper.run(sf);
                    } catch (Exception e) {
                        Log.e("MessageHelper", "下载并执行脚本时发生异常。" + e.getMessage());
                    }
                }
        );
        t.start();

    }

    /**
     * 模拟位置
     *
     * @param lat
     * @param lng
     */
    private void mockLocation(double lat, double lng) {
        /*Context acontext = App.getApp().getApplicationContext();
        final Intent mockIntent = new Intent(acontext, MockLocationSevice.class);
        ServiceConnection mockconn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder binder) {
                MockLocationSevice.MockLocationSeviceBinder serviceBinder = (MockLocationSevice.MockLocationSeviceBinder) binder;
                MockLocationSevice ser = serviceBinder.getService();
                ser.setLocationData(lat, lng);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        };
        acontext.bindService(mockIntent, mockconn, Service.BIND_AUTO_CREATE);*/
    }
}
